﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HCQ2_IBLL;
using HCQ2_Model;
using HCQ2_Model.Data;
using HCQ2_Model.Pay;
using HCQ2_Common;
using HCQ2_Model.ViewModel;
using System.Web;
using System.Transactions;

namespace HCQ2_BLL
{
    /// <summary>
    /// 新购物车相关
    /// </summary>
    public partial class N_ShoppingBLL: IN_ShoppingBLL
    {
        /// <summary>
        /// 添加进购物车
        /// </summary>
        /// <param name="shoppingAddParams">参数</param>
        /// <returns></returns>
        /// <remarks>
        /// 2020-3-24 17:00新增：购物车已经存在商品、商品被删除、商品已经下架三个提示信息
        /// 2021-9-14：添加需求《VLions需求规格_度度圈接口需求_订单及购物车-202100909.docx》的相关内容
        /// </remarks>
        public OperationResult ShoppingAdd(ShoppingAddParams shoppingAddParams)
        {
            T_DocumentInfo documentInfo = DBSession.IT_DocumentInfoDAL.FindSingle(w=>w.file_id==shoppingAddParams.CommodityId);
            if (documentInfo == null) {
                return new OperationResult(false,"未找到对应的商品信息");
            }
            if (documentInfo.file_status == 4)
            {
                return new OperationResult(false,"商品已经下架");
            }
            if (documentInfo.if_remove)
            {
                return new OperationResult(false,"商品已经被删除");
            }

            T_User user = DBSession.IT_UserDAL.FindSingle(w => w.user_guid.Equals(shoppingAddParams.userid));

            N_Shopping shoppingCommodity = GetShoppingCommodity(user.user_id, shoppingAddParams.CommodityId.Value);
            //2022-04-19：购物车存在 并且 规格一样才更新数量
            if (shoppingCommodity != null && CheckShoppingCommoditySpec(shoppingAddParams, user.user_id))
            {
                //2021-10-3:老谭微信提出，实物商品可以重复添加，更新数量
                shoppingCommodity.Quantity += shoppingAddParams.Quantity == null ? 1 : shoppingAddParams.Quantity.Value;

                //更新购物车数量
                DBSession.IN_ShoppingDAL.Modify(shoppingCommodity, w=>w.ShoppingId == shoppingCommodity.ShoppingId, "Quantity");

                return new OperationResult(true, "更新购物车数量成功");
                //return new OperationResult(false, "购物车已经存在此商品，请不要重复添加");
            }

            var commodityDetailedInfoParams = new List<PaymentAmountParamsCommodityInfo>(1);
            commodityDetailedInfoParams.Add(shoppingAddParams.MapTo<PaymentAmountParamsCommodityInfo>());
            List<PaymentAmountParamsCommodityDetailedInfo> paymentAmountParamsCommodityDetailedInfos = DBSession.IN_OrderDAL.ListPayCommodityDetailedInfo(commodityDetailedInfoParams);
            if (paymentAmountParamsCommodityDetailedInfos.Count == 0) {
                return new OperationResult(false, "获取不到商品的价格信息，请管理员检查是否正确设置商品各个期限的价格？");
            }

            N_Shopping shopping = new N_Shopping() {
                UserId = user.user_id,
                UserName = user.user_name,
                FileId = shoppingAddParams.CommodityId.Value,
                PurchasePeriod = shoppingAddParams.PurchasePeriod,
                CreateTime = DateTime.Now,
                CreateMoney = paymentAmountParamsCommodityDetailedInfos[0].OriPrice,
                //下面3个是，添加需求《VLions需求规格_度度圈接口需求_订单及购物车-202100909.docx》的相关内容
                StoreID = shoppingAddParams.StoreID,
                Quantity = shoppingAddParams.Quantity == null ? 1 : shoppingAddParams.Quantity.Value,
                OrderType = shoppingAddParams.OrderType == null ? 1 : shoppingAddParams.OrderType.Value
            };

            DBSession.IN_ShoppingDAL.Add(shopping);

            #region 禅道170号需求添加 规格列表

            if (shoppingAddParams.Specs != null && shoppingAddParams.Specs.Count > 0) {                
                foreach (SpecParamModel specParam in shoppingAddParams.Specs) {
                    N_Spec spec = new N_Spec();
                    //0购物车的、1订单的
                    spec.SpecType = 0;
                    //购物车ID
                    spec.SpecTypeId = shopping.ShoppingId;
                    //商品ID
                    spec.CommodityId = shoppingAddParams.CommodityId.Value;                    
                    spec.SpecName = specParam.SpecName;
                    spec.SpecValue = specParam.SpecValue;
                    spec.OptionId = specParam.OptionId;

                    DBSession.IN_SpecDAL.Add(spec);
                }
            }

            #endregion

            return new OperationResult(true,"添加进购物车成功");
        }

        /// <summary>
        /// 检测购物车中已经存在的商品对应的规格和添加的商品规格是否一样？当调用 GetShoppingCommodity 购物车存在添加的商品才使用这个检查
        /// </summary>
        /// <param name="shoppingAddParams"></param>
        /// <returns>true 一样、false 不一样</returns>
        private bool CheckShoppingCommoditySpec(ShoppingAddParams shoppingAddParams, int userId) 
        {
            //获取用户购物车中，当前添加商品的信息
            var userShoppings = DBSession.IN_ShoppingDAL.Select(w=>w.UserId == userId && w.FileId == shoppingAddParams.CommodityId);

            //规格是否一样
            bool result = false;
            //检查每条购物车数据的规格
            foreach (N_Shopping shopping in userShoppings) {                
                //购物车同一个商品的规格
                var specs = DBSession.IN_SpecDAL.Select(w => w.SpecType == 0 && w.SpecTypeId == shopping.ShoppingId);
                var specsDb = new List<SpecParamModel>(specs.Count);
                foreach (N_Spec s in specs) {
                    specsDb.Add(new SpecParamModel() { 
                        SpecName = s.SpecName,
                        SpecValue = s.SpecValue,
                        OptionId = s.OptionId
                    });
                }

                string a = JsonHelper.ObjectToJson(shoppingAddParams.Specs);
                string b = JsonHelper.ObjectToJson(specsDb);
                if (a.Equals(b)) {
                    result = true;
                    break;
                }
            }

            return result;
        }

        /// <summary>
        /// 获取购物车中是否已经存在指定商品
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="commodityId">商品ID</param>
        /// <returns>不为空存在、为空不存在</returns>
        private N_Shopping GetShoppingCommodity(int userId, int commodityId)
        {
            var shopping = DBSession.IN_ShoppingDAL.FindSingle(w => w.UserId == userId && w.FileId == commodityId);
            
            return shopping;
        }

        /// <summary>
        /// 判断购物车中是否已经存在指定商品
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="commodityId">商品ID</param>
        /// <returns>true存在、false不存在</returns>
        private bool ExistsShoppingCommodity(int userId,int commodityId)
        {
            var shopping = DBSession.IN_ShoppingDAL.FindSingle(w=>w.UserId==userId && w.FileId==commodityId);
            if (shopping == null)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 获取购物车列表
        /// </summary>
        /// <param name="shoppingListParams"></param>
        /// <returns></returns>
        public OperationResult<TableModel<List<ShoppingList>>> ShoppingList(ShoppingListParams shoppingListParams)
        {
            var data = DBSession.IN_ShoppingDAL.ShoppingList(shoppingListParams);
            var tableModel = data.Data;
            
            foreach (ShoppingList shoppingList in tableModel.rows)
            {
                shoppingList.FileImgUrl = shoppingList.FileImgUrl.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
            }

            data.Data = tableModel;
            return data;
        }

        /// <summary>
        /// 更新购物车列表
        /// </summary>
        /// <param name="shoppingUpdateParams"></param>
        /// <returns></returns>
        public OperationResult UpdateShopping(ShoppingUpdateParams shoppingUpdateParams)
        {
            T_User user = DBSession.IT_UserDAL.FindSingle(w=>w.user_guid.Equals(shoppingUpdateParams.userid));

            using (TransactionScope transactionScope = new TransactionScope()) {
                
                foreach (var shoppingUpdate in shoppingUpdateParams.CommodityIds)
                {                    
                    //找到购物车中的商品信息
                    var shoppingInfo = DBSession.IN_ShoppingDAL.FindSingle(d => d.FileId == shoppingUpdate.CommodityId.Value && d.UserId == user.user_id);
                    if (shoppingInfo == null) {
                        return new OperationResult(false,$"购物车中不存在商品ID：{shoppingUpdate.CommodityId} 的商品");
                    }

                    /*
                     * 删除购物车中商品对应的商品规格，条件：规格类别=0（购物车）、SpecTypeId=购物车Id、CommodityId=商品ID
                     * shoppingUpdate.Type=2删除购物车商品需要删除、shoppingUpdate.Type=1更新购物车信息也需要删除
                     */
                    DBSession.IN_SpecDAL.Delete(w => w.SpecType == 0
                        && w.SpecTypeId == shoppingInfo.ShoppingId && w.CommodityId == shoppingUpdate.CommodityId);

                    //删除购物车中商品
                    if (shoppingUpdate.Type == 2)
                    {
                        //删除购物车里面的商品
                        DBSession.IN_ShoppingDAL.Delete(d => d.FileId == shoppingUpdate.CommodityId.Value && d.UserId == user.user_id);
                    }

                    //更新购物车中商品购买期限
                    if (shoppingUpdate.Type == 1)
                    {
                        T_VRGoodDisiPrice t_VRGoodDisiPrice = DBSession.IT_VRGoodDisiPriceDAL.FindSingle(w=>w.file_id==shoppingUpdate.CommodityId && w.op_month==shoppingUpdate.PurchasePeriod.Value);
                        N_Shopping shopping = new N_Shopping() {
                            PurchasePeriod = shoppingUpdate.PurchasePeriod,
                            CreateMoney = t_VRGoodDisiPrice.ori_price
                        };

                        //更新购物车的商品
                        DBSession.IN_ShoppingDAL.Modify(shopping, w => w.FileId == shoppingUpdate.CommodityId && w.UserId == user.user_id, "PurchasePeriod", "CreateMoney");

                        //前面删除了商品规格，再次插入商品规格
                        if (shoppingUpdate.Specs.Count > 0)
                        {
                            foreach (SpecParamModel specParam in shoppingUpdate.Specs)
                            {
                                N_Spec spec = new N_Spec();
                                //0购物车的、1订单的
                                spec.SpecType = 0;
                                //购物车主键值
                                spec.SpecTypeId = shoppingInfo.ShoppingId;
                                //商品ID
                                spec.CommodityId = shoppingUpdate.CommodityId.Value;
                                spec.SpecName = specParam.SpecName;
                                spec.SpecValue = specParam.SpecValue;
                                spec.OptionId = specParam.OptionId;

                                DBSession.IN_SpecDAL.Add(spec);
                            }
                        }
                    }
                }

                transactionScope.Complete();
            }
            return new OperationResult(true,"更新购物车列表成功");
        }

        public OperationResult DeleteShopping(ShoppingDeleteParams param)
        {
            T_User user = DBSession.IT_UserDAL.FindSingle(w => w.user_guid.Equals(param.userid));

            using (TransactionScope transactionScope = new TransactionScope())
            {
                //找到购物车中的商品信息
                var shoppingInfo = DBSession.IN_ShoppingDAL.FindSingle(d => d.ShoppingId == param.ShoppingId && d.UserId == user.user_id);
                if (shoppingInfo == null)
                {
                    return new OperationResult(false, $"购物车中不存在购物车Id：{param.ShoppingId} 的商品");
                }

                //删除规格
                DBSession.IN_SpecDAL.Delete(w => w.SpecType == 0 && w.SpecTypeId == param.ShoppingId);

                //删除购物车里面的商品
                DBSession.IN_ShoppingDAL.Delete(d => d.ShoppingId == param.ShoppingId && d.UserId == user.user_id);

                transactionScope.Complete();
            }
            return new OperationResult(true, "删除购物车商品成功");
        }
    }
}
